package com.etoak.config.security.detailservice;

import com.etoak.web.sys_menu.entity.SysMenu;
import com.etoak.web.sys_menu.service.SysMenuService;
import com.etoak.web.sys_user.entity.SysUser;
import com.etoak.web.sys_user.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author by 孙有泽
 * @Date 2025/2/25 17:54
 * @Description
 */
@Component("customerUserDetailService")
public class CustomerUserDetailService  implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.loadUserByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<SysMenu> menuList=null;
        if(StringUtils.isNotEmpty(sysUser.getIsadmin()+"")&&"0".equals(sysUser.getIsadmin()+"")){
            menuList= sysMenuService.list();

        }else{
            menuList=sysMenuService.queryMenuByUserId(sysUser.getId());
        }
        List<String> collect = Optional.ofNullable(menuList).orElse(new ArrayList<>()).stream().
                filter(item -> item!=null&&StringUtils.isNotEmpty(item.getCode())).
                map(item -> item.getCode()).
                collect(Collectors.toList());
        String[] array = collect.toArray(new String[collect.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
        sysUser.setAuthorities(authorityList);
        return sysUser;
    }
}
